/**
 * Object Creation Tool
 * Author: Andrew Shore
 * 
 * Tool to assist in creating objects for a 3D RPG game for the PC
 * developed with Unity. User can choose to create 3 different types of objects,
 * an Item, an Enemy, or a NPC and can specify different characteristics of the
 * object like name, attributes, and the script associated with them. Objects
 * are saved in a directory under the same name as the object name so for example
 * a Item name Potion will be saved in /itemDirName/Potion. User can save or load
 * an object to edit in this tool.
 */
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.*;
import javax.swing.*;



public class ObjectCreationTool extends JFrame implements ActionListener {
    private final int WIDTH = 500;
    private final int HEIGHT = 500;
    private final int MAX_ATTR = 100;
    private final int MIN_ATTR = -100;
    private final int MIN_LEVEL = 1;
    private final int MAX_LEVEL = 100;
    private final int MAX_NUM_SCRIPTS = 10;
    private static final String ITEM_DIR_NAME = "CreatedItems";
    private static final String ENEMY_DIR_NAME= "CreatedEnemies";
    private static final String NPC_DIR_NAME = "CreatedNPCs";
    
  //used to reset GUI when user selects new object type
    boolean isReset = false;	
    
    Container container;
    JPanel objectTypePanel = new JPanel(new FlowLayout());
    
    //list of all attributes for a item or enemy, any change made here
    //will be reflected in the tool so to add more attributes just add to this array
    String[] attributesList = {"","Health","Mana","Strength","Agility",
    		                   "Speed","Defense","Att Power", "Intelligence","Spell power"};

    
    //creates components for enemy form
    JPanel enemyScriptPanel = new JPanel();
	JTextField enemyNameText = new JTextField(15);
	JTextField enemyLevelText = new JTextField(3);
	JPanel attrSubPanel = new JPanel();
    
	//creates component for item form
	JPanel itemAttrPanel = new JPanel(); 
	JPanel itemScriptPanel = new JPanel();
	JTextField itemNameText = new JTextField(15);
    
    //private static final BoxLayout LAYOUT_STYLE= new BoxLayout();
	
	/**
	 * Default constructor for this class. Called once in the main.
	 */
	public ObjectCreationTool(){
		super();
		super.setSize(WIDTH, HEIGHT);
		super.setTitle("Object Creation Tool");
		
		super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	
		this.setup();
		
	}
	
	/**
	 * This constructor is called by the Load action for each object. It resets the GUI when a user wants
	 * to load an object into the tool and then calls the load function. 
	 * @param string
	 */
	public ObjectCreationTool(String string) {
		// TODO Auto-generated constructor stub
		
		super();
		super.setSize(WIDTH, HEIGHT);
		super.setTitle("Object Creation Tool");
		
		super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	
		this.setup();
		
		if(string.equals("LoadItem")){
			this.setupItemForm();
			this.loadItem();
		}else if(string.equals("LoadEnemy")){
			this.setupEnemyForm();
			this.loadEnemy();
		}
	}
	
	/**
	 * Function to load data from a text File into the enemy form. Data is read from a text file
	 * named after the item, parsed, and then put into the appropriate field. The function creates
	 * new attribute and script panels when they enter data into one so that more data can be entered.
	 */
	private void loadItem() {
		// TODO Auto-generated method stub
		
		int nextPos = 0;
		String fileName;
		String[] loadAttributesName = new String[attributesList.length];
		String[] loadAttrMagnitude = new String[attributesList.length];
		String[] loadScripts = new String[MAX_NUM_SCRIPTS];
		fileName = JOptionPane.showInputDialog(container, "File Name:");
		String itemName;
		File inputFile = new File(ITEM_DIR_NAME ,fileName);
		
		try {
			Scanner inputStream = new Scanner(inputFile);
			inputStream.nextLine();		//reads "Item Name:" header so next line can read actual item name
			itemName = inputStream.nextLine();
			inputStream.nextLine();		//reads "Attributes:" header text
			
			//reads in the attributes for the item
			while(inputStream.hasNextLine()){
				String attrName = inputStream.next();
				if(!attrName.equals("Scripts:")){
					String attrMagn = inputStream.next();
					loadAttributesName[nextPos] = attrName;
					loadAttrMagnitude[nextPos] = attrMagn;
					nextPos++;
				}else{
					//breaks when we reach the scripts
					break;
				}
			
			}
			
			//reads in the attached scripts for the item
			inputStream.nextLine();
			nextPos = 0;
			while(inputStream.hasNextLine()){
				String temp = inputStream.nextLine();
				loadScripts[nextPos] = temp;
				nextPos++;
			}
			
			
			itemNameText.setText(itemName);
			//loads attribute names into combo boxes and magnitudes into text fields
			for(int i = 0; i < loadAttributesName.length; i++){
				Component[] attrComp = itemAttrPanel.getComponents(); 
				Component[] attrPanel = ((JPanel) attrComp[i]).getComponents();
				if(loadAttributesName[i] != null && loadAttrMagnitude[i] != null){
					((JComboBox) attrPanel[0]).setSelectedItem(loadAttributesName[i]);
					((JTextField)attrPanel[1]).setText(loadAttrMagnitude[i]);
					
				}else{
					break;
				}
			}
			
			//loads script names into text fields
			for(int i = 0; i < loadScripts.length; i++){
				Component[] scriptComp = itemScriptPanel.getComponents();
				Component[] scriptPanel = ((JPanel)scriptComp[i]).getComponents();
				if(loadScripts[i] != null){
					((JTextField)scriptPanel[1]).setText(loadScripts[i]);
					attachItemScript(((JButton)scriptPanel[2]));
				}
				else{
					break;
				}
			}
			
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
		
	/**
	 * Function to load data from a text File into the enemy form. Data is read from a text file
	 * named after the item, parsed, and then put into the appropriate field. The function creates
	 * new attribute and script panels when they enter data into one so that more data can be entered.
	 */
	private void loadEnemy(){
		int nextPos = 0;
		String fileName;
		//String[] loadAttributesName = new String[attributesList.length];
		String[] loadAttrMagnitude = new String[attributesList.length];
		String[] loadScripts = new String[MAX_NUM_SCRIPTS];
		fileName = JOptionPane.showInputDialog(container, "File Name:");
		String enemyName;
		String enemyLevel;
		File inputFile = new File(ITEM_DIR_NAME ,fileName);
		
		Scanner inputStream;
		try {
			inputStream = new Scanner(inputFile);
			inputStream.nextLine();		//reads "Enemy Name:" header text
			enemyName = inputStream.nextLine();
			inputStream.nextLine();		//reads "Enemy Level:" header text
			enemyLevel = inputStream.nextLine();
			
			//Gets components of attrSubPanel which contains the attribute names and magnitudes
			//in a scrollable list
			
			for(int i = 0; i < attributesList.length - 1; i++){
				//reads in attribute name, uses loop because attributes may have multiple  
				// words such as "Spell Power"
				while((!inputStream.hasNextInt()) && inputStream.hasNext()){
					inputStream.next();
				}
				//reads magnitude of attribute
				if(inputStream.hasNextInt()){
					//inputStream.next();		//reads Attribute name, not needed because we know the order of the attributes
					loadAttrMagnitude[i] = Integer.toString(inputStream.nextInt());		//gets magnitude from JTextField
					inputStream.nextLine();	
				}else{
					break;
				}
				
			}
			
			inputStream.nextLine();		//reads "Scripts:" header text
			nextPos = 0;
			while(inputStream.hasNextLine()){
				String temp = inputStream.nextLine();
				loadScripts[nextPos] = temp;
				nextPos++;
			}
			
			//sets name and level
			enemyNameText.setText(enemyName);
			enemyLevelText.setText(enemyLevel);
			
			//loads attribute magnitudes into text fields
			Component[] attrSubPanelComp = attrSubPanel.getComponents();
			for(int i = 0; i < attributesList.length - 1; i++){
				//gets the components of the next JPanel in the attrSubPanel, each Attribue JPanel
				// contains the JLabel for the attribute name and the JTextField for the attribute
				// magnitude, in that order
				Component[] currentAttr = ((JPanel) attrSubPanelComp[i]).getComponents();
				if(loadAttrMagnitude[i] != null){
					((JTextField)currentAttr[1]).setText(loadAttrMagnitude[i]);
				}else{
					break;
				}
			}
			
			//loads script names into text fields
			for(int i = 0; i < loadScripts.length; i++){
				//Gets components of enemyScriptPanel, each component is a Jpanel that contains a JLabel
				//for Scripts:, a text field for the script name, and a button to attach more scripts
				//(in that order)
				Component[] scriptComp = enemyScriptPanel.getComponents();
				Component[] scriptPanel = ((JPanel)scriptComp[i]).getComponents();
				
				if(loadScripts[i] != null){
					((JTextField)scriptPanel[1]).setText(loadScripts[i]);
					attachEnemyScript(((JButton)scriptPanel[2]));  //adds a new Script panel
				}
				else{
					break;
				}
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(container, "Error:File not found");
		}
		
		
		
		
	}

	/**
	 * Function to set up the the JFrame and container and also adds the object type panel
	 *  so user can select an object to create. Sets the layout of various components and
	 *  also creates the directories where the objects are stored.
	 */
	public void setup(){
		//sets maximum size of components 
        setMaxSize();
        enemyScriptPanel.setLayout(new BoxLayout(enemyScriptPanel, BoxLayout.Y_AXIS));
        itemScriptPanel.setLayout(new BoxLayout(itemScriptPanel, BoxLayout.Y_AXIS));
		itemAttrPanel.setLayout(new BoxLayout(itemAttrPanel, BoxLayout.Y_AXIS));
		
		//Adds action listener to combo box so appropriate form is loaded when user selects object
	    String[] type = {"" , "Item" , "Enemy" , "NPC"};
		JLabel objectTypeLabel = new JLabel("Object Type");
		JComboBox objectComboBox = new JComboBox(type);
		objectComboBox.addActionListener(this);
		objectComboBox.setActionCommand("Object Type");
	
		objectTypePanel.add(objectTypeLabel);
		objectTypePanel.add(objectComboBox);
		
	
	    //sets up container, adds the object type panel
		container = this.getContentPane();
		container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
		container.add(objectTypePanel);
		
		//creates directory for created items if it doesn't already exist
		File dirFileItem = new File(ITEM_DIR_NAME );
		if(!dirFileItem.exists()){
			
			if(!dirFileItem.mkdir()){
				JOptionPane.showMessageDialog(container, 
						"Error: Directory: " + dirFileItem.getName() + " cannot" +
								" be created");
			}
		}
		
		//creates directory for created enemies if it doesn't already exist
		File dirFileEnemy = new File(ITEM_DIR_NAME );
		if(!dirFileEnemy.exists()){
			
			if(!dirFileEnemy.mkdir()){
				JOptionPane.showMessageDialog(container, 
						"Error: Directory: " + dirFileEnemy.getName() + " cannot" +
								" be created");
			}
		}
		
		
	}

	
	/**
	 * This function sets maximum size of all components initialized in setup
	 */
	public void setMaxSize(){
		itemAttrPanel.setMaximumSize(new Dimension(500,25));
		itemScriptPanel.setMaximumSize(new Dimension(500, 25));
		enemyScriptPanel.setMaximumSize(new Dimension(500,25));
		objectTypePanel.setMaximumSize(new Dimension(500,50));
		
	}


	/**
	 * Handles action events such as combo boxes and buttons. 
	 * List of action events:
	 * 			"Object Type" - when user selects an object type from drop down menu
	 * 			"New Attr" - when user selects an attribute from the bottom most attribute box it
	 * 						adds a new attribute box
	 * 			"
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		//when user selects object appropriate form is loaded
		if(e.getActionCommand().equals("Object Type")){
			
			JComboBox cb = (JComboBox)e.getSource();
			String type = (String)cb.getSelectedItem();
			
			if(type.equals("Item")){
				setupItemForm();
			}else if(type.equals("Enemy")){
				setupEnemyForm();
			}else if(type.equals("NPC")){
				setupNPCForm();
			}	
		}
		//adds new attribute field when user selects an attribute from the drop down box
		else if(e.getActionCommand().equals("New Attr")){
			
			JComboBox cb = (JComboBox)e.getSource();
			addNewAttr(cb);
			
		}
		//Adds new script panel to enemy form when user presses the "Attach more" button
		else if(e.getActionCommand().equals("Attach more enemy scripts")){
			JButton button = (JButton)e.getSource();
			attachEnemyScript(button);
		
			
		}
		//Adds new script panel to item form when user presses the "Attach more" button
		else if(e.getActionCommand().equals("Attach more item scripts")){
			JButton button = (JButton)e.getSource();
			attachItemScript(button);
		 
		}
		//Saves info in enemy form to a text file
		else if(e.getActionCommand().equals("Save Enemy")){
			saveEnemy();
	
			
			
		}
		//loads data into enemy form from text file
		else if(e.getActionCommand().equals("Load Enemy")){
			this.setVisible(false);
			ObjectCreationTool window = new ObjectCreationTool("LoadEnemy");
			window.setVisible(true);
		}
		//saves data from item form into text file
		else if(e.getActionCommand().equals("Save Item")){
			saveItem();
		}
		//loads data into item form from text file
		else if(e.getActionCommand().equals("Load Item")){
			this.setVisible(false);
			ObjectCreationTool window = new ObjectCreationTool("LoadItem");
			window.setVisible(true);
		}
			
	}

	/*
	 * This Function creates a new TextField when user presses the attach more scripts button
	 */
	private void attachItemScript(JButton button) {
		// TODO Auto-generated method stub
		   button.setVisible(false);
		    
		    JPanel tempPanel = new JPanel(new GridLayout(0,3));
		    tempPanel.setMaximumSize(new Dimension(500,25));
		    JLabel newScriptLabel = new JLabel("Script Name:");
		    JTextField newScriptText = new JTextField(10);
		    JButton newScriptButton = new JButton("Attach more scripts");
		    newScriptButton.addActionListener(this);
		    
		    //increases max size of itemScriptPanel and adds components
		    itemScriptPanel.setMaximumSize(new Dimension(500,itemScriptPanel.getMaximumSize().height + 25));
		    tempPanel.add(newScriptLabel);
		    tempPanel.add(newScriptText);
		    tempPanel.add(newScriptButton);
		    itemScriptPanel.add(tempPanel);
		    
			//container.remove(button);
		    itemScriptPanel.validate();
		    itemScriptPanel.repaint();
			container.validate();
			container.repaint();
		
	}

	/*
	 * This Function attachs a new Textfield when the user presses the attach more script button.
	 */
	private void attachEnemyScript(JButton button) {
		// TODO Auto-generated method stub
	    button.setVisible(false);
	    
	    JPanel newScriptPanel = new JPanel(new GridLayout(0,3));
	    JLabel newScriptLabel = new JLabel("Script Name:");
	    JTextField newScriptText = new JTextField(10);
	    JButton newScriptButton = new JButton("Attach more");
	    newScriptButton.addActionListener(this);
	    
	    //increases max size of itemScriptPanel and adds components
	    enemyScriptPanel.setMaximumSize(new Dimension(500,enemyScriptPanel.getMaximumSize().height + 25));
	    newScriptPanel.setMaximumSize(new Dimension(500, 25));
	    newScriptPanel.add(newScriptLabel);
	    newScriptPanel.add(newScriptText);
	    newScriptPanel.add(newScriptButton);
	    enemyScriptPanel.add(newScriptPanel);
	    
		//container.remove(button);
	    enemyScriptPanel.validate();
	    enemyScriptPanel.repaint();
		container.validate();
		container.repaint();
		
	}

	private void setupNPCForm() {
		// TODO Auto-generated method stub
		
	}

	/*
	 * This function creates the GUI for the Create Enemy Form. If this is the second time an object
	 * type is selected than the GUI is reset by disabling this window and opening a new one.
	 */
	private void setupEnemyForm() {
		// TODO Auto-generated method stub
		
		//reset is set to true after user selects an object type so
		//if they select another type than the window is reset
		if(isReset){
			//disables this window
			this.setVisible(false);
			//creates new window to reset GUI
			ObjectCreationTool window = new ObjectCreationTool();
			
			//this sets the location to the new window to be the same as
			//this window
			Point pos = this.getLocation();
			window.setLocation(pos);
			window.setVisible(true);
			return;
		}
		
		//objectComboBox.setSelectedItem(2); 
	
		//creates label and text field for enemy name
		JPanel enemyNamePanel = new JPanel(new FlowLayout());
		JLabel enemyNameLabel = new JLabel("Enemy Name:");
		enemyNamePanel.add(enemyNameLabel);
		enemyNamePanel.add(enemyNameText);
		enemyNamePanel.setMaximumSize(new Dimension(500,25));
		
		

		//Creates label and text field for attached scripts
		JPanel tempScriptPanel = new JPanel(new GridLayout(0,3));
		JLabel enemyScriptLabel = new JLabel("Script Name:");
		JTextField enemyScriptText = new JTextField(10);
		JButton moreEnemyScripts = new JButton("Attach more Scripts");
		moreEnemyScripts.setActionCommand("Attach more enemy scripts");
		moreEnemyScripts.addActionListener(this);
		tempScriptPanel.add(enemyScriptLabel);
		tempScriptPanel.add(enemyScriptText);
		tempScriptPanel.add(moreEnemyScripts);
		tempScriptPanel.setMaximumSize(new Dimension(500,25));
		enemyScriptPanel.add(tempScriptPanel);
		
		
		//creates entry for enemy level
		JPanel enemyLevelPanel = new JPanel(new FlowLayout());
		JLabel enemyLevelLabel = new JLabel("Level");
		enemyLevelPanel.add(enemyLevelLabel);
		enemyLevelPanel.add(enemyLevelText);
		enemyLevelPanel.setMaximumSize(new Dimension(500, 25));
		
		
		//creates a header text for the attributes scrollPane
		JPanel enemyAttrPanel = new JPanel(new BorderLayout());	
		enemyAttrPanel.setMaximumSize(new Dimension(500,25));
		JPanel enemyAttrHeader = new JPanel(new FlowLayout());
		enemyAttrHeader.setMaximumSize(new Dimension(500,25));
		JLabel enemyAttrLabel = new JLabel("Attributes");
		enemyAttrHeader.add(enemyAttrLabel);
		
		attrSubPanel.setLayout(new GridLayout(0,3));
		fillEnemyAttr(attrSubPanel);
		
		//creates a save and a load button
		JPanel enemySaveLoadPanel = new JPanel(new FlowLayout());
		JButton enemySaveButton = new JButton("Save Enemy");
		JButton enemyLoadButton = new JButton("Load Enemy");
		enemySaveButton.addActionListener(this);
	    enemyLoadButton.addActionListener(this);
	    enemySaveLoadPanel.add(enemySaveButton);
	    enemySaveLoadPanel.add(enemyLoadButton);
	    	
		container.add(enemyNamePanel);
		container.add(enemyLevelPanel);
		container.add(enemyAttrHeader);
		
		
		//creates scrollPane for Attributes
		enemyAttrPanel.add(attrSubPanel, BorderLayout.CENTER);
		JScrollPane scrollpane = new JScrollPane(attrSubPanel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
				                                   JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		scrollpane.setMaximumSize(new Dimension(500,75));
		getContentPane().add(scrollpane, BorderLayout.CENTER);
		
		//adds new panel to container and repaints it
		container.add(enemyAttrPanel);
		container.add(enemyScriptPanel);
		container.add(enemySaveLoadPanel);
		container.validate();
		container.repaint();
		isReset = true;
		
	}

	/*
	 * This function creates the GUI for the enemy attribute panel. New attributes can be easily added
	 * without changing the code in this function by adding the attributes to the array attributesList.
	 */
	private void fillEnemyAttr(JPanel panel) {
		// TODO Auto-generated method stub
		
		for(int i = 1; i < attributesList.length ; i++){
			JPanel tempPanel = new JPanel(new FlowLayout());
			JLabel tempLabel = new JLabel(attributesList[i]);
			JTextField tempText = new JTextField(6);
			tempPanel.setMaximumSize(new Dimension(500,25));
			tempPanel.add(tempLabel);
			tempPanel.add(tempText);
			panel.add(tempPanel);
			tempText.setName(attributesList[i]);
			panel.setName(attributesList[i]);
			
			
		}
	}

	/*
	 * This function sets up the GUI for the Create Item Form. If it is the second object type to be
	 * selected then the window is reset.
	 */
	private void setupItemForm() {
		// TODO Auto-generated method stub
		
		if(isReset){
			this.setVisible(false);
			ObjectCreationTool window = new ObjectCreationTool();
		
			//this sets the location to the new window to be the same as
			//this window
			Point pos = this.getLocation();
			window.setLocation(pos);
			window.setVisible(true);
			
			return;
		}
	
		
		//creates label and text field for item name
		JPanel itemNamePanel = new JPanel(new FlowLayout());
		JLabel itemNameLabel = new JLabel("Item Name:");
		itemNamePanel.add(itemNameLabel);
		itemNamePanel.add(itemNameText);
		itemNamePanel.setMaximumSize(new Dimension(500,50));
		
		//creates drop down box for attributes and text field for magnitude
		JPanel tempPanel = new JPanel(new GridLayout(0,2));
		JComboBox itemAttributes = new JComboBox(attributesList);
		JTextField itemAttrText = new JTextField(6);
		itemAttributes.addActionListener(this);
		itemAttributes.setActionCommand("New Attr");
		tempPanel.add(itemAttributes);
		tempPanel.add(itemAttrText);
		tempPanel.setMaximumSize(new Dimension(500,25));
		itemAttrPanel.add(tempPanel);
		
		
		//Creates label and text field for attached scripts
		JPanel tempScriptPanel = new JPanel(new GridLayout(0,3));
		tempScriptPanel.setMaximumSize(new Dimension(500,25));
		JLabel itemScriptLabel = new JLabel("Script Name:");
		JTextField itemScriptText = new JTextField(10);
		JButton moreItemScripts = new JButton("Attach more scripts");
		moreItemScripts.setActionCommand("Attach more item scripts");
		moreItemScripts.addActionListener(this);
		tempScriptPanel.add(itemScriptLabel);
		tempScriptPanel.add(itemScriptText);
		tempScriptPanel.add(moreItemScripts);
		itemScriptPanel.add(tempScriptPanel);
		
		//creates component for save and load button
		JPanel itemSaveLoadPanel = new JPanel(new FlowLayout());
		JButton itemSaveButton = new JButton("Save Item");
		JButton itemLoadButton = new JButton("Load Item");
		itemSaveButton.addActionListener(this);
		itemLoadButton.addActionListener(this);
		itemSaveLoadPanel.add(itemSaveButton);
		itemSaveLoadPanel.add(itemLoadButton);
		
		
		//adds new panels to container and repaints it
		container.add(itemNamePanel);
		container.add(itemAttrPanel);
		container.add(itemScriptPanel);
		container.add(itemSaveLoadPanel);
		container.validate();
		container.repaint();
		isReset = true;
	}
	
	/*
	 * Adds a new ComboBox and TextField for the item Attributes. Called when user selects 
	 * an item from the bottom most comboBox
	 */
	public void addNewAttr(JComboBox cb){
		
		if(!((String)cb.getSelectedItem()).equals("")){
			//removes action listener on previous attribute selector
			//so we can add one to the new one
			cb.removeActionListener(this);
			
			//adds new attribute combo box and text field
			JPanel tempPanel = new JPanel(new GridLayout(0,2));
			JComboBox newAttr = new JComboBox(attributesList);
			newAttr.addActionListener(this);
			newAttr.setActionCommand("New Attr");
			JTextField newAttrText = new JTextField(6);
			
			//increases max size of JPanel and adds combo box and text field
			tempPanel.setMaximumSize(new Dimension(500, 25));
			tempPanel.add(newAttr);
			tempPanel.add(newAttrText);
		    itemAttrPanel.setMaximumSize(new Dimension(500,itemAttrPanel.getMaximumSize().height + 25));
			itemAttrPanel.add(tempPanel);
			
			//validates and repaints itemAttrPanel and container
			itemAttrPanel.validate();
			itemAttrPanel.repaint();
			container.validate();
			container.repaint();
		}
	}
	/*
	 * This function saves the values in the Create Item form to a text file named after the
	 * Item Name. All fields must be filled in and have an appropriate value except for the 
	 * last attribute panel and last script panel.
	 */
	public void saveItem(){
		String itemName;
		String fileName;
		File newFile;
		String[] attributeName = new String[attributesList.length];
		int[] attributeMagnitude = new int[attributesList.length];
		String[] scriptName = new String[MAX_NUM_SCRIPTS];
		
		itemName = itemNameText.getText();
		//item name must have a value
		if((itemName.equals(""))){
			JOptionPane.showMessageDialog(container, "Please enter a name for the item");
			return;
		}else{
			fileName = itemName;
			newFile = new File(ITEM_DIR_NAME , fileName);
			
		}
		
		try {
			PrintWriter output = new PrintWriter(newFile);
			
			//since the attribute panels are generic and don't have names we must get all components from
			//the panel and iterate through them to get the data. 
			Component[] attrComponents = itemAttrPanel.getComponents();
			for(int i = 0; i < attrComponents.length; i++){
				if(attrComponents[i].getClass().getName().equals("javax.swing.JPanel")){
					//gets subpanels, each subPanel consists of a ComboBox, and TextField
					Component[] tempComp = ((JPanel) attrComponents[i]).getComponents();
					
					//gets only the attributes that have been selected
					if(!((String) ((JComboBox) tempComp[0]).getSelectedItem()).equals("")){
						attributeName[i] = (String) ((JComboBox) tempComp[0]).getSelectedItem();
						//if the value for the selected attribute is nonempty we add it to the array of 
						//attributes to output later
						if(!((JTextField)tempComp[1]).getText().equals("")){
							//makes sure the magnitude for the attribute is a valid number
							try{
								
								attributeMagnitude[i] = Integer.parseInt(((JTextField)tempComp[1]).getText());
								//attribute magnitude must be within valid range
								if(attributeMagnitude[i] < MIN_ATTR || attributeMagnitude[i] > MAX_ATTR){
									JOptionPane.showMessageDialog(container, "Error: Magnitude for " + 
											         attributeName[i] +  " is out of range.");
									return;
								}
							}catch(NumberFormatException e){
								JOptionPane.showMessageDialog(container, "Please enter a valid number for " + attributeName[i]);
								return;
							}
							//}
							
						}else{
							JOptionPane.showMessageDialog(container, "Please enter a value for " + attributeName[i]);
						}
						
					}
				}
				
			}
			//gets script panels and iterates through them since there can be any number of them
			//and they do not have names
			Component[] scriptComponents = itemScriptPanel.getComponents();
			for(int i = 0; i < scriptComponents.length; i++){
				if(scriptComponents[i].getClass().getName().equals("javax.swing.JPanel")){
					Component[] tempComp = ((JPanel) scriptComponents[i]).getComponents();
					//script name must be nonempty to add it to text file, Note: no scripts have to 
					//be attached in order to save the item
					if(!((JTextField) tempComp[1]).getText().equals("")){
						scriptName[i] = ((JTextField) tempComp[1]).getText();
					}
				}
				
			}
			
			//prints the data to the text file
			output.println("Item Name:");
			output.println(itemName);
			output.println("Attributes:");
			for(int i = 0; i < attributeName.length; i++){
				if(attributeName[i] != null){
					output.println(attributeName[i] + " " + attributeMagnitude[i]);
				}
			}
			output.println("Scripts:");
			for(int i = 0; i < scriptName.length; i++){
				if(scriptName[i] != null){
					output.println(scriptName[i]);
				}
			}
			
			output.close();
			JOptionPane.showMessageDialog(container,"Save Successful");
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	/*
	 * Function to save an enemy to a text file named after the name of the enemy. All fields must be filled
	 * in and have a valid value for a successful save except for attached scripts.
	 */
	public void saveEnemy(){
		int[] attributesListMagn = new int[attributesList.length];
		String[] scriptList = new String[MAX_NUM_SCRIPTS];
		int enemyLevel = -1;
		String enemyLevelStr = enemyLevelText.getText();
		String enemyName = enemyNameText.getText();
		String fileName = enemyName;
		File newEnemyFile;
		
		//opens file named after enemy if Enemy Name textField is nonempty
		if(enemyName.equals("")){
			JOptionPane.showMessageDialog(container, "Please enter a name for the enemy");
			return;
		}else{
			newEnemyFile = new File(ITEM_DIR_NAME ,fileName);
		}
		
		
		try {
			PrintWriter output = new PrintWriter(newEnemyFile);
			
			//reads Level from textField, must be nonempty and within valid range
			if(!enemyLevelStr.equals("")){
				//Enemy Level must be an integer
				try{
					enemyLevel = Integer.parseInt(enemyLevelStr);	
				}catch(NumberFormatException e){
					JOptionPane.showMessageDialog(container,"Error:Enter an integer for Enemy Level");
					return;
				}
			}else{
				JOptionPane.showMessageDialog(container, "Error: Please enter value for level");
				return;
			}
			if(enemyLevel < MIN_LEVEL || enemyLevel > MAX_LEVEL){
				//Level must be within a valid range
				JOptionPane.showMessageDialog(container, "Error: level out of range");
				return;
			}
			
		    //gets an array of JPanel components that contain the attribute components
			Component[] attrComp = attrSubPanel.getComponents(); 
			//loops through components and gets magnitudes of attribute changes
			for(int i = 0; i < attrComp.length; i++){
				if(attrComp[i].getClass().getName().equals("javax.swing.JPanel")){
					//gets components of the JPanel within attrSubPanel, each Panel contains a JLabel,
					//and JTextField, in that order
					Component[] tempComp = ((JPanel) attrComp[i]).getComponents();
					//attribute field must be nonempty
					if(!((JTextField) tempComp[1]).getText().equals("")){
						try{
							attributesListMagn[i + 1] = Integer.parseInt(((JTextField) tempComp[1]).getText());	
						}catch(NumberFormatException e){
							JOptionPane.showMessageDialog(container, "Error: Please enter a integer for " +
													attributesList[i + 1]);
							return;
						}
						
						//attribute must be within valid range
						if(attributesListMagn[i + 1] < MIN_ATTR || attributesListMagn[i + 1] > MAX_ATTR){
							JOptionPane.showMessageDialog(container, "Error: Attr out of range");
							return;
						}
					}else{
						JOptionPane.showMessageDialog(container, "Error: Please enter value for " +
								                       attributesList[i + 1]);
						return;
				
					}
				}
			}
			//gets an array of JPanel components that contain the script components
			Component[] scriptComp = enemyScriptPanel.getComponents();
			for(int i = 0; i < scriptComp.length; i++){
				if(scriptComp[i].getClass().getName().equals("javax.swing.JPanel")){
					//gets components of the JPanel within scriptPanel, each Panel contains a JLabel,
					//JTextField, and JButton, in that order
					Component[] tempComp = ((JPanel) scriptComp[i]).getComponents();
					//user not required to enter a script to attach
					if(!(((JTextField) tempComp[1]).getText().equals(""))){
						//gets text from textField of script panel which is the second component
						//in the panel, hence tempComp[1]
						scriptList[i] = ((JTextField) tempComp[1]).getText();
					}
				}
			}
			
			//outputs data to file
			output.println("Enemy Name:");
			output.println(enemyName);
			output.println("Level:");
			output.println(enemyLevel);
			output.println("Attributes:");
			for(int i = 1; i < attributesList.length; i++){
				output.println(attributesList[i] + " " + attributesListMagn[i]);
			}
			output.println("Scripts:");
			for(int i = 0; i < scriptList.length; i++){
				if(scriptList[i] != null){
					output.println(scriptList[i]);
				}
			}
			output.close();
			
			JOptionPane.showMessageDialog(container, "Save Successful");
			
			
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
	}

/**
 * @param args
 */
public static void main(String[] args){
	// TODO Auto-generated method stub

	ObjectCreationTool tool = new ObjectCreationTool();
	tool.setVisible(true);
}

}